import { defineStore } from 'pinia'

export const usePermissionStore = defineStore('permission', {
    state: () => ({
        users: [],
        roles: [
            { value: 0, label: '访客', code: 'guest' },
            { value: 1, label: '管理员', code: 'admin' },
            { value: 2, label: '管理者', code: 'manager' },
            { value: 3, label: '成员', code: 'member' }
        ],
        locationUsers: [],
        currentLocationId: null,
        loading: false,
        userLocationPermissions: {},
    }),

    getters: {
        getUserById: (state) => (id) => {
            return state.users.find(user => user.id === id)
        },

        getActiveUsers: (state) => {
            return state.users.filter(user => user.status === 'active')
        },

        getRoleByValue: (state) => (value) => {
            return state.roles.find(role => role.value === value)
        },

        getRoleByCode: (state) => (code) => {
            return state.roles.find(role => role.code === code)
        },

        getUsersWithRole: (state) => (roleValue) => {
            return state.users.filter(user => user.role === roleValue)
        },

        getLocationUsers: (state) => {
            return state.locationUsers
        },

        getUserRoleForLocation: (state) => (locationId) => {
            const roleId = state.userLocationPermissions[String(locationId)];
            return typeof roleId === 'string' ? Number(roleId) : roleId;
        },

        canManageLocationUsers: (state) => (locationId) => {
            const roleId = state.userLocationPermissions[String(locationId)];
            const roleIdNum = typeof roleId === 'string' ? Number(roleId) : roleId;
            return roleIdNum === 1 || roleIdNum === 2;
        },

        canViewUserPermissions: (state) => (locationId) => {
            const roleId = state.userLocationPermissions[String(locationId)];
            const roleIdNum = typeof roleId === 'string' ? Number(roleId) : roleId;
            return roleIdNum === 1 || roleIdNum === 2;
        }
    },

    actions: {
        addUser(user) {
            const id = Math.max(0, ...this.users.map(u => u.id)) + 1
            const newUser = {
                id,
                userId: id,
                username: user.username,
                email: user.email,
                password: user.password,
                role: user.role,
                status: user.status,
                lastLogin: '-'
            }
            this.users.push(newUser)
            return newUser
        },

        updateUser(user) {
            const index = this.users.findIndex(u => u.id === user.id)
            if (index !== -1) {
                this.users[index] = { ...this.users[index], ...user }
            }
        },

        deleteUser(id) {
            const index = this.users.findIndex(u => u.id === id)
            if (index !== -1) {
                this.users.splice(index, 1)
            }
        },

        toggleUserStatus(id) {
            const user = this.getUserById(id)
            if (user) {
                user.status = user.status === 'active' ? 'inactive' : 'active'
            }
        },

        updateRolePermissions(roleValue, permissions) {
            const index = this.roles.findIndex(r => r.value === roleValue)
            if (index !== -1) {
                this.roles[index].permissions = [...permissions]
            }
        },

        hasPermission(userRoleValue, permission) {
            console.warn('hasPermission 方法可能需要根据新的角色结构调整')
            return true;
        },

        setLocationUsers(users, locationId) {
            this.locationUsers = users || []
            this.currentLocationId = locationId
        },

        clearLocationUsers() {
            this.locationUsers = []
            this.currentLocationId = null
        },

        setLoading(status) {
            this.loading = status
        },

        setUserLocationPermissions(permissionsData) {
            if (permissionsData && typeof permissionsData === 'object') {
                console.log('原始位置权限数据:', permissionsData);
                console.log('位置权限数据类型:', Object.keys(permissionsData).map(key => {
                    return {
                        locationId: key,
                        roleType: permissionsData[key],
                        roleTypeType: typeof permissionsData[key]
                    };
                }));

                this.userLocationPermissions = permissionsData;
                console.log('用户位置权限已更新:', this.userLocationPermissions);
            } else {
                this.userLocationPermissions = {};
                console.warn('设置的用户位置权限数据格式不正确', permissionsData);
            }
        },

        clearUserLocationPermissions() {
            this.userLocationPermissions = {};
        },

        // 获取位置的用户列表
        async fetchLocationUsers(locationId) {
            if (!locationId) {
                console.warn('fetchLocationUsers: 未提供locationId');
                return;
            }

            try {
                this.setLoading(true);
                // 导入locationsApi
                const { locationsApi } = await import('../utils/apiService');

                // 调用API获取位置用户数据
                const response = await locationsApi.getLocationUsers(locationId);

                if (response && response.data) {
                    this.setLocationUsers(response.data, locationId);
                    console.log('位置用户数据已更新:', response.data);
                    return response.data;
                } else {
                    console.warn('获取位置用户数据为空');
                    this.setLocationUsers([], locationId);
                    return [];
                }
            } catch (error) {
                console.error('获取位置用户数据失败:', error);
                this.clearLocationUsers();
                throw error;
            } finally {
                this.setLoading(false);
            }
        },

        // 获取角色列表
        async fetchRoles() {
            try {
                // 这里可以调用API获取角色列表
                // 现在我们使用本地定义的角色
                console.log('使用本地定义的角色数据');
                return this.roles;
            } catch (error) {
                console.error('获取角色数据失败:', error);
                throw error;
            }
        },

        // 获取用户位置权限
        async loadUserLocationPermissions() {
            try {
                // 导入locationsApi和useUserStore
                const { locationsApi } = await import('../utils/apiService');
                const { useUserStore } = await import('./user');
                const userStore = useUserStore();

                // 获取当前用户ID
                let userId = userStore.getUser?.id;

                // 如果无法从store获取，尝试从localStorage获取
                if (!userId) {
                    try {
                        const userJson = localStorage.getItem('user');
                        if (userJson && userJson !== 'undefined') {
                            const userData = JSON.parse(userJson);
                            userId = userData.id;
                            console.log('从localStorage获取到用户ID:', userId);
                        }
                    } catch (err) {
                        console.error('解析localStorage中的用户信息失败', err);
                    }
                }

                if (!userId) {
                    console.warn('无法获取用户ID，跳过位置权限获取');
                    return false;
                }

                console.log('正在获取用户位置权限，用户ID:', userId);
                const response = await locationsApi.getUserLocationPermissions(userId);

                if (response && response.code === 200 && response.data) {
                    this.setUserLocationPermissions(response.data);
                    console.log('用户位置权限已加载');
                    return true;
                } else {
                    console.warn('获取用户位置权限失败:', response);
                    return false;
                }
            } catch (error) {
                console.error('获取用户位置权限出错:', error);
                return false;
            }
        }
    }
}) 